package com.gaoding.qa.auto.converter;

import com.dtflys.forest.converter.json.ForestJacksonConverter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gaoding.commons.util.JsonMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * json转换器
 * @author mobai
 * @since 2021/9/22 14:59
 */
@Slf4j
public class JsonConverter extends ForestJacksonConverter {

    @SneakyThrows
    @Override
    public String encodeToString(Object obj) {
        return JsonMapper.defaultMapper().toJson(obj);
    }


    @Override
    public <T> T convertToJavaObject(String source, Type targetType) {
        ObjectMapper mapper = JsonMapper.defaultMapper().getMapper();
        try {
            return mapper.readValue(source, mapper.getTypeFactory().constructType(targetType));
        } catch (IOException e) {
            log.error("反序列化失败，响应值:{},接口的返回类型:{}",source,targetType,e);
            throw new RuntimeException("反序列化失败");
        }

    }



}
